import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    jwt: sessionStorage.getItem('jwt'),
    userInfo: JSON.parse(sessionStorage.getItem('userInfo')),
    loggedIn: false,
    collectedImageIdList: [],
    followingUserIdList: [],
    hasNewMessage: sessionStorage.getItem('hasNewMessage')
  },
  mutations: {
    SET_JWT: (state, jwt) => {
      state.jwt = jwt
      sessionStorage.setItem('jwt', jwt)
      if (jwt) {
        state.loggedIn = true
      }
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
      if (userInfo) state.loggedIn = true
    },
    // 删除jwt及userInfo
    REMOVE_INFO: (state) => {
      state.jwt = ''
      state.userInfo = {}
      state.loggedIn = false
      sessionStorage.removeItem('jwt')
      sessionStorage.removeItem('userInfo')
      sessionStorage.removeItem('hasNewMessage')
    },
    SET_LOGGEDIN_TRUE: (state) => {
      state.loggedIn = true
    },
    switch_collect: (state, imageId) => {
      const index = state.collectedImageIdList.indexOf(imageId)
      if (index === -1) {
        state.collectedImageIdList.push(imageId)
      } else {
        state.collectedImageIdList.splice(index, 1)
      }
    },
    switch_follow: (state, userId) => {
      const index = state.followingUserIdList.indexOf(userId)
      if (index === -1) {
        state.followingUserIdList.push(userId)
      } else {
        state.followingUserIdList.splice(index, 1)
      }
    },
    set_new_message: (state, param) => {
      state.hasNewMessage = param
      sessionStorage.setItem('hasNewMessage', param)
    }
  },
  // get: 获取用户信息及token
  getters: {
    getUserInfo: state => {
      return state.userInfo
    },
    getJWT: state => {
      return state.jwt
    },
    getCurrentUserId: state => {
      return state.userInfo.id
    }
  },
  actions: {
  },
  modules: {
  }
})
